﻿package com.sxhalo.manage.web.action;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sxhalo.manage.map.*;
import com.sxhalo.manage.service.IBaseService;
import com.sxhalo.manage.utils.DateUtil;
import com.sxhalo.manage.utils.Pager;
import com.sxhalo.manage.web.form.ProjectsForm;

public class ProjectsAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private int draw = 1;

	private int start = 0;

	private int length = 20;

	private ProjectsForm projects;

	// 将会被Struts2序列化为JSON字符串的对象
	private Map<String, Object> dataMap;

	private List dataList;

	// 业务层
	private IBaseService<Projects> myService;
	
	private IBaseService<Task> taskService;

	private IBaseService<SysUsers> userService;
	
	private IBaseService<Company> companyService;
	
	private IBaseService<Department> departService;
	
	private IBaseService<ProjectPriority> priorityService;
	
	private IBaseService<ProjectStatus> statusService;
	
	private IBaseService<ProjectType> typeService;

	public int getDraw() {
		return draw;
	}

	public void setDraw(int draw) {
		this.draw = draw;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public ProjectsForm getProjects() {
		return projects;
	}

	public void setProjects(ProjectsForm projects) {
		this.projects = projects;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public List getDataList() {
		return dataList;
	}

	public void setDataList(List dataList) {
		this.dataList = dataList;
	}

	public IBaseService<Projects> getMyService() {
		return myService;
	}

	public void setMyService(IBaseService<Projects> myService) {
		this.myService = myService;
	}

	public IBaseService<SysUsers> getUserService() {
		return userService;
	}

	public void setUserService(IBaseService<SysUsers> userService) {
		this.userService = userService;
	}

	public IBaseService<Company> getCompanyService() {
		return companyService;
	}

	public void setCompanyService(IBaseService<Company> companyService) {
		this.companyService = companyService;
	}

	public IBaseService<Department> getDepartService() {
		return departService;
	}

	public void setDepartService(IBaseService<Department> departService) {
		this.departService = departService;
	}

	public IBaseService<ProjectPriority> getPriorityService() {
		return priorityService;
	}

	public void setPriorityService(IBaseService<ProjectPriority> priorityService) {
		this.priorityService = priorityService;
	}

	public IBaseService<ProjectStatus> getStatusService() {
		return statusService;
	}

	public void setStatusService(IBaseService<ProjectStatus> statusService) {
		this.statusService = statusService;
	}

	public IBaseService<ProjectType> getTypeService() {
		return typeService;
	}

	public void setTypeService(IBaseService<ProjectType> typeService) {
		this.typeService = typeService;
	}

	public IBaseService<Task> getTaskService() {
		return taskService;
	}

	public void setTaskService(IBaseService<Task> taskService) {
		this.taskService = taskService;
	}

	/**
	 * 构造方法
	 */
	public ProjectsAction() {
		// 初始化Map对象
		dataMap = new HashMap<String, Object>();
	}
	
	public String getForm(){
		List<Company> clist = companyService.findAll();
		int comid = 0;
		if(clist.size()>0){
			comid = clist.get(0).getCompanyId();
		}
		List<SysUsers> ulist = getCompanyUser(comid);
		List<Department> dlist = departService.findList("companyId", comid);
		try {
			Projects entity = myService.findById(projects.getProjectId());
			projects.setProjectCompany(entity.getCompany().getCompanyId());
			projects.setProjectCompanyInternal(entity.getProjectCompanyInternal());
			projects.setProjectName(entity.getProjectName());
			projects.setProjectShortName(entity.getProjectShortName());
			projects.setProjectOwner(entity.getProjectOwner().getUserId());
			projects.setProjectUrl(entity.getProjectUrl());
			projects.setProjectDemoUrl(entity.getProjectDemoUrl());
			projects.setProjectStartDate(DateUtil.format(entity.getProjectStartDate()));
			projects.setProjectEndDate(DateUtil.format(entity.getProjectEndDate()));
			projects.setProjectStatus(entity.getProjectStatus().getProjectStatusId());
			projects.setProjectPercentComplete(entity.getProjectPercentComplete());
			projects.setProjectColorIdentifier(entity.getProjectColorIdentifier());
			projects.setProjectDescription(entity.getProjectDescription());
			projects.setProjectTargetBudget(entity.getProjectTargetBudget());
			projects.setProjectActualBudget(entity.getProjectActualBudget());
			projects.setProjectCreator(entity.getProjectCreator());
			projects.setProjectDepartments(entity.getDepartment().getCompanyId());
			projects.setProjectContacts(entity.getProjectContacts());
			projects.setProjectPriority(entity.getProjectPriority().getProjectPriorityId());
			projects.setProjectType(entity.getProjectType().getProjectTypeId());
			//用户取值
			ulist = getCompanyUser(entity.getDepartment().getCompanyId());
			//部门取值
			dlist = departService.findList("companyId", entity.getDepartment().getCompanyId());

		} catch (Exception re) {

		}
		ActionContext.getContext().put("clist", clist);
		ActionContext.getContext().put("dlist", dlist);
		ActionContext.getContext().put("ulist", ulist);
		ActionContext.getContext().put("plist", priorityService.findAll());
		ActionContext.getContext().put("slist", statusService.findAll());
		ActionContext.getContext().put("tlist", typeService.findAll());
		// 返回结果
		return SUCCESS;
	}

	public String getEntity() {
		try {
			Projects entity = myService.findById(projects.getProjectId());
			projects.setProjectCompany(entity.getCompany().getCompanyId());
			projects.setProjectCompanyName(entity.getCompany().getCompanyName());
			projects.setProjectCompanyInternal(entity.getProjectCompanyInternal());
			projects.setProjectName(entity.getProjectName());
			projects.setProjectShortName(entity.getProjectShortName());
			projects.setProjectOwner(entity.getProjectOwner().getUserId());
			projects.setProjectUrl(entity.getProjectUrl());
			projects.setProjectDemoUrl(entity.getProjectDemoUrl());
			projects.setProjectStartDate(DateUtil.format(entity.getProjectStartDate()));
			projects.setProjectEndDate(DateUtil.format(entity.getProjectEndDate()));
			projects.setProjectStatus(entity.getProjectStatus().getProjectStatusId());
			projects.setProjectStatusName(entity.getProjectStatus().getProjectStatusName());
			projects.setProjectPercentComplete(entity.getProjectPercentComplete());
			projects.setProjectColorIdentifier(entity.getProjectColorIdentifier());
			projects.setProjectDescription(entity.getProjectDescription());
			projects.setProjectTargetBudget(entity.getProjectTargetBudget());
			projects.setProjectActualBudget(entity.getProjectActualBudget());
			projects.setProjectCreator(entity.getProjectCreator());
			projects.setProjectDepartments(entity.getDepartment().getCompanyId());
			projects.setProjectDepartmentName(entity.getDepartment().getDepartmentName());
			projects.setProjectContacts(entity.getProjectContacts());
			projects.setProjectPriority(entity.getProjectPriority().getProjectPriorityId());
			projects.setProjectPriorityName(entity.getProjectPriority().getProjectPriorityName());
			projects.setProjectType(entity.getProjectType().getProjectTypeId());
			projects.setProjectTypeName(entity.getProjectType().getProjectTypeName());
		} catch (Exception re) {

		}
		// 返回结果
		return SUCCESS;
	}

	public String getGridData() {
		// dataMap中的数据将会被Struts2转换成JSON字符串，所以这里要先清空其中的数据
		dataMap.clear();
		HttpServletRequest request = ServletActionContext.getRequest();
		// 获取数据
		try {
			//updateComplete();//更新项目进度
			String where = "";//初始化where
			String projectStatus = request.getParameter("ProjectStatus");
			if(projectStatus!=null && !projectStatus.equals("")){
				where += " projectStatus = "+ projectStatus; 
			}
			String projectname = request.getParameter("name");
			if(projectname!=null && !projectname.equals("")){
				where = where.equals("") ? "" : where+" and";
				where += " projectName like '%"+ projectname+"%'"; 
			}
			String projectType = request.getParameter("type");
			if(projectType!=null && !projectType.equals("")){
				where = where.equals("") ? "" : where+" and";
				where += " projectType = "+ projectType; 
			}
			String company = request.getParameter("cid");
			String proComp =  request.getParameter("proComp");
			if(null!=company && null!=proComp){
				where = where.equals("") ? "" : where+" and";
				where += " company.companyId = "+ company;
				if("1".equals(proComp)){
					where += " and projectStatus = 6"; 				
				}else{
					where += " and projectStatus < 6"; 
				}
			}
			int page = start == 0 ? 1 : start / length + 1;
			int size = length < 0 ? Integer.MAX_VALUE : length;
			Pager<Projects> list = myService.findPagerList(page, size, where, "");
			dataMap.put("draw", draw);
			dataMap.put("recordsTotal", list.getTotal());
			dataMap.put("recordsFiltered", list.getTotal());
			dataMap.put("data", copyList(list.getList()));
		} catch (Exception re) {
			dataMap.put("data", re.getMessage());
		}
		// 返回结果
		return SUCCESS;
	}

	public String addEntity() {
		// 清空dataMap中的数据
		dataMap.clear();
		Timestamp startDate = Timestamp.valueOf(projects.getProjectStartDate());
		Timestamp endDate = Timestamp.valueOf(projects.getProjectEndDate());

		Projects entity = new Projects();
		Company company = new Company();
		company.setCompanyId(projects.getProjectCompany());
		entity.setCompany(company);
		entity.setProjectCompanyInternal(projects.getProjectCompanyInternal());
		entity.setProjectName(projects.getProjectName());
		entity.setProjectShortName(projects.getProjectShortName());
		SysUsers user = new SysUsers();
		user.setUserId(projects.getProjectOwner());
		entity.setProjectOwner(user);
		entity.setProjectUrl(projects.getProjectUrl());
		entity.setProjectDemoUrl(projects.getProjectDemoUrl());
		entity.setProjectStartDate(startDate);
		entity.setProjectEndDate(endDate);
		ProjectStatus projectStatus = new ProjectStatus();
		projectStatus.setProjectStatusId(projects.getProjectStatus());
		entity.setProjectStatus(projectStatus);
		entity.setProjectPercentComplete(projects.getProjectPercentComplete());
		entity.setProjectColorIdentifier(projects.getProjectColorIdentifier());
		entity.setProjectDescription(projects.getProjectDescription());
		entity.setProjectTargetBudget(projects.getProjectTargetBudget());
		entity.setProjectActualBudget(projects.getProjectActualBudget());
		entity.setProjectCreator(projects.getProjectCreator());
		Department department = new Department();
		department.setDepartmentId(projects.getProjectDepartments());
		entity.setDepartment(department);
		entity.setProjectContacts(projects.getProjectContacts());
		ProjectPriority projectPriority = new ProjectPriority();
		projectPriority.setProjectPriorityId(projects.getProjectPriority());
		entity.setProjectPriority(projectPriority);
		ProjectType projectType = new ProjectType();
		projectType.setProjectTypeId(projects.getProjectType());
		entity.setProjectType(projectType);
		try {
			myService.save(entity);
			dataMap.put("data", true);
		} catch (Exception re) {
			dataMap.put("data", re.getMessage());
		}
		// 返回结果
		return SUCCESS;
	}

	public String editEntity() {
		// 清空dataMap中的数据
		dataMap.clear();
		Timestamp startDate = Timestamp.valueOf(projects.getProjectStartDate());
		Timestamp endDate = Timestamp.valueOf(projects.getProjectEndDate());
		Projects entity = myService.findById(projects.getProjectId());
		Company company = new Company();
		company.setCompanyId(projects.getProjectCompany());
		entity.setCompany(company);
		entity.setProjectCompanyInternal(projects.getProjectCompanyInternal());
		entity.setProjectName(projects.getProjectName());
		entity.setProjectShortName(projects.getProjectShortName());
		SysUsers user = new SysUsers();
		user.setUserId(projects.getProjectOwner());
		entity.setProjectOwner(user);
		entity.setProjectUrl(projects.getProjectUrl());
		entity.setProjectDemoUrl(projects.getProjectDemoUrl());
		entity.setProjectStartDate(startDate);
		entity.setProjectEndDate(endDate);
		ProjectStatus projectStatus = new ProjectStatus();
		projectStatus.setProjectStatusId(projects.getProjectStatus());
		entity.setProjectStatus(projectStatus);
		entity.setProjectPercentComplete(projects.getProjectPercentComplete());
		entity.setProjectColorIdentifier(projects.getProjectColorIdentifier());
		entity.setProjectDescription(projects.getProjectDescription());
		entity.setProjectTargetBudget(projects.getProjectTargetBudget());
		entity.setProjectActualBudget(projects.getProjectActualBudget());
		entity.setProjectCreator(projects.getProjectCreator());
		Department department = new Department();
		department.setDepartmentId(projects.getProjectDepartments());
		entity.setDepartment(department);
		entity.setProjectContacts(projects.getProjectContacts());
		ProjectPriority projectPriority = new ProjectPriority();
		projectPriority.setProjectPriorityId(projects.getProjectPriority());
		entity.setProjectPriority(projectPriority);
		ProjectType projectType = new ProjectType();
		projectType.setProjectTypeId(projects.getProjectType());
		entity.setProjectType(projectType);
		try {
			myService.update(entity);
			dataMap.put("data", true);
		} catch (Exception re) {
			dataMap.put("data", re.getMessage());
		}
		// 返回结果
		return SUCCESS;
	}

	public String delEntity() {
		// 清空dataMap中的数据
		dataMap.clear();
		try {
			Projects entity = myService.findById(projects.getProjectId());
				if(myService.delete(entity)){
					dataMap.put("valid", true);
				} else {
					dataMap.put("valid", false);
				}
			} catch (Exception re) {
				dataMap.put("valid", false);
			}
		// 返回结果
		return SUCCESS;
	}
	
	private List<ProjectsForm> copyList(List<Projects> list){
		List<ProjectsForm> data = new ArrayList<ProjectsForm>();
		for (Projects po : list) {
			ProjectsForm vo = new ProjectsForm();
			vo.setProjectId(po.getProjectId());
			vo.setProjectName(po.getProjectName());
			vo.setProjectPercentComplete(po.getProjectPercentComplete());
			vo.setProjectCompanyName(po.getCompany().getCompanyName());
			vo.setProjectDepartmentName(po.getDepartment().getDepartmentName());
			vo.setUserinfoTruename(po.getProjectOwner().getSysUserinfo().getUserinfoTruename());
			vo.setProjectPriorityName(po.getProjectPriority().getProjectPriorityName());
			vo.setProjectTypeName(po.getProjectType().getProjectTypeName());
			vo.setProjectStatusName(po.getProjectStatus().getProjectStatusName());
			vo.setProjectStartDate(po.getStartDate());
			vo.setProjectEndDate(po.getEndDate());
			vo.setProjectTargetBudget(po.getProjectTargetBudget());
			vo.setProjectActualBudget(po.getProjectActualBudget());
			data.add(vo);
		}
		return data;
	}
	
	public List<SysUsers> getCompanyUser(Integer companyId) {
		List<SysUsers> list = new ArrayList<SysUsers>();
		List<SysUsers> users = userService.findAll();
		for (SysUsers u : users) {
			if (u.getSysUserinfo().getCompany().getCompanyId() == companyId) {
				list.add(u);
			}
		}
		return list;
	}
	
	public void updateComplete(){
		List<Projects> list = myService.findAll();
		for (Projects po : list) {
			List<Task> task = taskService.findList("taskProject.projectId", po.getProjectId());
			if(task.size() > 0){
				Integer comSum = 0;
				for (Task t:task) {
					comSum+=t.getTaskPercentComplete();
				}
				double x = comSum*1.0;
				double y = 100*task.size()*1.0;
				double complete =x/y*100;
				DecimalFormat df1 = new DecimalFormat("0");
				po.setProjectPercentComplete(Short.parseShort(df1.format(complete)));
			}else{
				po.setProjectPercentComplete(Short.parseShort("0"));
			}
			try{
				myService.update(po);
			}catch(Exception re){
				
			}
		}
	}
	
	public String getProjectType(){
		dataList = typeService.findAll();
		return SUCCESS;
	}
	
	public String getProjectStatus(){
		dataList = statusService.findAll();
		return SUCCESS;
	}
	
	public String getProjectPriority(){
		dataList = priorityService.findAll();
		return SUCCESS;
	}
}
